package com.twq.patternmatch

/**
 * Created by tangweiqun on 2017/12/9.
 */
object CourseContent {
  def main(args: Array[String]): Unit = {
    //1、使用模式匹配
    val i = 3
    val result = i match {
      case 1 => 1
      case 2 => 2
      case 3 => 3
      case _ => -1
    }

    println(result)

    //2、case class和模式匹配配合
    abstract class Animal
    case class Cat(name: String) extends Animal
    case class Dog(color: String) extends Animal

    val dog: Animal = new Dog("red")
    dog match {
      case Cat(name) => println(name)
      case Dog(color) => println(color)
      case _ => println("not animal")
    }

    //3、模式匹配与unapply(萃取器)
    val emailStr: String = "laotang@qq.com"
    emailStr match {
      case EMail(user, domain) => println(user + " @ " + domain)
      case _ => println("not an email address")
    }
  }
}

object EMail {

  def unapply(str: String): Option[(String, String)] = {
    val parts = str split "@"
    if (parts.length == 2) Some(parts(0), parts(1)) else None
  }

}

